<template>
  <div class="table">
    <div class="content-common">
      <div class="header-title">土壤水分监测成果</div>
      <!-- 顶部搜索条件-->
      <div class="search-top">
        <el-form :label-position="'top'" :inline="true" :model="query">
          <el-form-item label="站点类型">
            <el-select style="width: 127px" v-model="query.stType" filterable clearable placeholder="请选择" :disabled="isView" @change="typeChange">
              <el-option v-for="item in stTypeList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="站点名称">
            <el-select style="width: 160px" v-model="query.stcd" filterable clearable placeholder="请选择">
              <el-option v-show="item.stType == query.stType" v-for="item in stationData" :key="item.stcd" :label="item.stnm" :value="item.stcd"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="小区" v-if="query.stType !== 2">
            <el-select style="width: 100px" v-model="query.areaCode" filterable clearable placeholder="请选择">
              <el-option v-for="item in areaCodeList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="计算方法">
            <el-select style="width: 90px" v-model="query.calType" filterable clearable placeholder="请选择">
              <el-option v-for="item in calTypeList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="起讫年份">
            <year-range-picker :yearRange="query.yearRange" @yearChanged="handleYearChanged"></year-range-picker>
          </el-form-item>
        </el-form>
      </div>
      <!-- 数据预览文字 -->
      <div class="data-preview" v-if="query.stType == 1">
        <div v-for="(item, index) in tableData" :key="index" :class="`preview-item item-${index}`" :style="`background-color: ${bgColors[index]};`">
          <div class="preview-item-text">
            全年土壤水分监测次数为 <span class="total">{{ item.tdrNums + item.dryNums }}</span> 次，其中TDR法次数为 <span class="">{{ item.tdrNums }}</span> 次；烘干法次数为
            <span class="">{{ item.dryNums }}</span> 次；采用烘干法测得土壤重量含水量，含水量为<span class="total">{{ item.minSoilMoisture }}</span> %~<span class="total">{{
              item.maxSoilMoisture
            }}</span>
            %。
            <div v-for="(children, idx) in item.detailList">
              <span class="left-dot"></span><span style="margin-left: 20px; font-weight: 400"> {{ children.areaCode }} 号小区：</span>
              <span style="width: 35px; display: inline-block">{{ children.minSoilMoisture }} </span> % ~ <span style="width: 35px; display: inline-block">{{ children.maxSoilMoisture }}</span> % ,
              平均含水量为 <span class="total" :style="children.isMax ? `color: red` : children.isMin ? `color: #00b600` : ``">{{ children.avgSoilMoisture }}</span> % 。
            </div>
          </div>

          <el-button :style="`background-color:${colors[index]}`" round>{{ item.year }}</el-button>
        </div>
      </div>
      <div class="data-preview" v-if="query.stType == 2">
        <div v-for="(item, index) in tableData" :key="index" :class="`preview-item item-${index}`" :style="`background-color: ${bgColors[index]};`">
          <div class="preview-item-text">
            全年土壤水分监测次数为 <span class="total">{{ item.tdrNums + item.dryNums }}</span> 次；采用烘干法测得土壤重量含水量，含水量为 <span class="total">{{ item.minSoilMoisture }}</span> %~<span
              class="total"
              >{{ item.maxSoilMoisture }}</span
            >
            % ,平均含水量为 <span class="total">{{ item.avgSoilMoisture }}</span> % 。
          </div>

          <el-button :style="`background-color:${colors[index]}`" round>{{ item.year }}</el-button>
        </div>
      </div>
      <!-- 数据预览图表 -->
      <div class="data-preview" style="margin-top: 20px">
        <div class="left" id="leftChart"></div>
        <div class="right" id="rightChart"></div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getSoilMoistureStatisticsrunoffField,
  listAreaDict, //列表查询小区字典
  listSoilMoistureStatistics,
  sysdictviewlistDictItem, //列表查询降雨年统计
  viewPageStationInfo,
  getSoilMoistureStatisticssmallbasin
} from '../../../api/index';
import YearRangePicker from '../../../components/common/YearRangePicker.vue';
let leftChart = null;
let rightChart = null;
export default {
  name: 'zhengbianguancao',
  components: { YearRangePicker },
  data() {
    return {
      globalUser: [],
      page: {
        currentPage: 1,
        pageSize: 10,
        totalPage: 0,
        totalSize: 0
      },
      query: {
        stcd: JSON.parse(sessionStorage.getItem('userInfo')).stcdList[0].stcd,
        stType: 1,
        yearRange: [`${new Date().getFullYear()}` - 1, `${new Date().getFullYear()}`],
        areaCode: null,
        calType: 1
      },

      formInline: {},
      tableData: [],
      pageTotal: 0,
      stationData: [],
      areaCodeList: [],
      checkArr: [],
      tijiaoform: {
        status: 1
      },
      isView: false,
      dialogMes: {
        show: false,
        query: {}
      },
      stTypeList: [
        { label: '坡面径流场', value: 1 },
        { label: '小流域控制站', value: 2 }
      ],
      calTypeList: [
        { label: 'TRD法', value: 1 },
        { label: '烘干法', value: 2 }
      ],
      bgColors: ['hsla(215, 100%, 71%, 0.2)', 'hsla(106, 67%, 58%, 0.2)'], //图示颜色
      colors: ['#69A8FF', '#6DDC4C'], //图示颜色
      chartsData: [],
      showChart: false,
      sourceMap: {}, //小区数据图谱
      loading: false
    };
  },
  mounted() {
    this.globalUser = globalUser;
    this.query.year = globalyear;
    this.getlistAreaDict();
    this.getData();
    this.getstationData();
    this.getchecktype();
  },
  watch: {
    'query.stType': {
      //切换站点类型时重新请求数据
      handler(newVal) {
        const currentList = this.stationData.filter((item) => item.stType == newVal);
        if (newVal == 2) {
          // 默认小区为1
          this.query.areaCode = 1;
          this.query.stcd = currentList[0].stcd;
        } else {
          // 默认小区为空
          this.query.areaCode = null;
          this.query.stcd = currentList[0].stcd;
        }
        this.$nextTick(() => {
          this.getlistSoilMoistureStatistics();
        });
      }
    },
    'query.yearRange': {
      //选择年份
      handler(newVal) {
        if (newVal) {
          this.getData();
          this.$nextTick(() => {
            this.getlistSoilMoistureStatistics();
          });
        }
      }
    },
    // 切换站点名称
    'query.stcd': {
      //站点名称
      handler(newVal) {
        this.getData();
        this.getlistAreaDict();
      }
    },
    'query.calType': {
      //站点类型
      handler(newVal) {
        if (newVal) {
          this.getData();
          this.getlistAreaDict();
        }
      }
    },
    'query.areaCode': {
      //切换小区时重新请求数据
      handler(newVal) {
        this.$nextTick(() => {
          this.getlistSoilMoistureStatistics();
        });
      }
    },
    $route: {
      handler(newVal) {
        if (newVal.path.indexOf('jingliunisha') > -1) {
        }
      },
      immediate: true
    }
  },
  // 清除图表
  unmounted() {
    if (leftChart) {
      leftChart.dispose();
      leftChart = null;
    }
    if (rightChart) {
      rightChart.dispose();
      rightChart = null;
    }
  },
  methods: {
    // 数据处理
    reformData() {},
    //获取坡面径流场 stType为1 echarts数据
    async getlistSoilMoistureStatistics() {
      let yearBegin = this.query.yearRange[0] || '';
      let yearEnd = this.query.yearRange[1] || '';
      if (yearBegin === '') {
        return this.$message.error('请选择开始年份!');
      }
      if (yearEnd === '') {
        return this.$message.error('请选择结束年份!');
      }
      const sourceMap = {};
      //stType为1（坡面径流场）时根据小区号areaCodeList长度调取接口，然后拼接数据，图例为多条折线，
      if (this.query.stType == 1) {
        if (this.query.areaCode) {
          const res = await listSoilMoistureStatistics({
            stcd: this.query.stcd || '',
            stType: this.query.stType,
            yearBegin: yearBegin,
            yearEnd: yearEnd,
            calType: this.query.calType,
            areaCode: this.query.areaCode
            // year: 2022
          });
          res.object.forEach((item) => {
            if (sourceMap[item.year]) {
              // 判断日期是否在dateArr里
              if (!sourceMap[item.year].dateArr.includes(item.obDate)) {
                sourceMap[item.year].dateArr.push(item.obDate);
              }
              // 填充数据
              if (sourceMap[item.year][item.areaCode]) {
                sourceMap[item.year][item.areaCode][item.obDate] = { ...item };
              } else {
                sourceMap[item.year][item.areaCode] = {
                  [item.obDate]: { ...item }
                };
              }
            } else {
              // 初始化该年份数据
              sourceMap[item.year] = {
                dateArr: [item.obDate],
                [item.areaCode]: {
                  [item.obDate]: { ...item }
                }
              };
            }
          });
          this.$nextTick(() => {
            this.initChart(sourceMap);
          });
        } else {
          this.areaCodeList.forEach(async (area) => {
            const res = await listSoilMoistureStatistics({
              stcd: this.query.stcd || '',
              stType: this.query.stType,
              yearBegin: yearBegin,
              yearEnd: yearEnd,
              calType: this.query.calType,
              areaCode: area.areaCode
              // year: 2022
            });

            // 区分年份
            // 先获取日期，按日期填充数据
            res.object.forEach((item) => {
              if (sourceMap[item.year]) {
                // 判断日期是否在dateArr里
                if (!sourceMap[item.year].dateArr.includes(item.obDate)) {
                  sourceMap[item.year].dateArr.push(item.obDate);
                }
                // 填充数据
                if (sourceMap[item.year][item.areaCode]) {
                  sourceMap[item.year][item.areaCode][item.obDate] = { ...item };
                } else {
                  sourceMap[item.year][item.areaCode] = {
                    [item.obDate]: { ...item }
                  };
                }
              } else {
                // 初始化该年份数据
                sourceMap[item.year] = {
                  dateArr: [item.obDate],
                  [item.areaCode]: {
                    [item.obDate]: { ...item }
                  }
                };
              }
            });
          });

          // this.$nextTick(() => {
          //   this.initChart(sourceMap);
          // });
          setTimeout(() => {
            this.initChart(sourceMap);
          }, 300);
        }
      } else {
        //stType为2（小流域控制站）默认areaCode为1，处理数据，图例为单条折线
        //   获取数据
        const res = await getSoilMoistureStatisticssmallbasin({
          stcd: this.query.stcd || '',
          stType: 2,
          yearBegin: yearBegin,
          yearEnd: yearEnd,
          calType: this.query.calType
        });
        this.tableData = res.object;

        let arr = [];
        for (let i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].detailList) {
            arr = arr.concat(this.tableData[i].detailList);
          }
        }
        for (let i = 0; i < arr.length; i++) {
          arr[i].year = arr[i].obDate.substring(0, 4);
        }
        arr.forEach((item) => {
          if (sourceMap[item.year]) {
            // 判断日期是否在dateArr里
            if (!sourceMap[item.year].dateArr.includes(item.obDate)) {
              sourceMap[item.year].dateArr.push(item.obDate);
            }
            // 填充数据
            if (sourceMap[item.year]) {
              sourceMap[item.year][item.obDate] = { ...item };
            } else {
              sourceMap[item.year] = {
                [item.obDate]: { ...item }
              };
            }
          } else {
            // 初始化该年份数据
            sourceMap[item.year] = {
              dateArr: [item.obDate],
              [item.obDate]: { ...item }
            };
          }
        });

        setTimeout(() => {
          // this.initChart(sourceMap, 1);
          this.initChart(sourceMap, 1);
        }, 300);
      }
    },
    objectToArray(arr) {
      let _data = arr;
      for (let i = 0; i < _data.length; i++) {
        let tmp = Object.entries(_data[i]).map(([key, d]) => {
          if (d.length > 0) {
            let obj = {
              label: key + '号小区',
              ...d
            };
            return obj;
          } else {
            return {
              label: key + '号小区',
              ...d
            };
          }
        });
        _data[i].arr = tmp.filter((e) => {
          return e.label !== 'year号小区' && e.label !== 'dateArr号小区';
        });
      }
      return _data;
    },
    compareMinMax(arr) {
      if (arr.length === 0) {
        return null; // 如果数组为空，则返回null
      }
      let newArr = [];
      for (let i = 0; i < arr.length; i++) {
        newArr.push(arr[i].avgSoilMoisture);
      }
      const result = newArr.reduce(
        (acc, curr) => ({
          min: Math.min(acc.min, curr),
          max: Math.max(acc.max, curr)
        }),
        { min: newArr[0], max: newArr[0] }
      );
      arr.map((item) => {
        item.isMax = item.avgSoilMoisture == result.max ? true : false;
        item.isMin = item.avgSoilMoisture == result.min ? true : false;
      });
      return arr;
    },
    getData() {
      let yearBegin = this.query.yearRange[0] || '';
      let yearEnd = this.query.yearRange[1] || '';
      if (yearBegin === '') {
        return this.$message.error('请选择开始年份!');
      }
      if (yearEnd === '') {
        return this.$message.error('请选择结束年份!');
      }
      if (this.query.stType == 1) {
        let data = {
          stcd: this.query.stcd || '',
          stType: 1,
          yearBegin: yearBegin,
          yearEnd: yearEnd,
          calType: this.query.calType
        };
        //   获取数据
        getSoilMoistureStatisticsrunoffField(data).then((res) => {
          this.tableData = res.object;
          // 根据日期和小区列表填充数据
          for (let i = 0; i < this.tableData.length; i++) {
            this.compareMinMax(this.tableData[i].detailList);
          }
        });
      } else {
        let data = {
          stcd: this.query.stcd || '',
          stType: 2,
          yearBegin: yearBegin,
          yearEnd: yearEnd,
          calType: this.query.calType
        };
        //   获取数据
        getSoilMoistureStatisticssmallbasin(data).then((res) => {
          this.tableData = res.object;
        });
      }
    },
    getlistAreaDict() {
      if (this.query.stcd === '' || !this.query.stcd) {
        return this.$message.error('请选择站点名称!');
      }
      listAreaDict({ stcd: this.query.stcd }).then((res) => {
        this.areaCodeList = res.object;
        for (let i = 0; i < this.areaCodeList.length; i++) {
          this.areaCodeList[i].label = this.areaCodeList[i].areaCode + '号小区';
          this.areaCodeList[i].value = Number(this.areaCodeList[i].areaCode);
        }
        this.$nextTick(() => {
          this.getlistSoilMoistureStatistics();
        });
      });
    },
    handleYearChanged(val) {
      this.query.yearRange = val;
    },
    initChart(sourceMap, isOption2) {
      const chartArr = [];
      const optionArr = [];
      Object.keys(sourceMap).forEach((key, index) => {
        chartArr.push(key);
        optionArr[index] = {
          title: {
            text: key + '年度'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: [],
            top: '5%'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          toolbox: {},
          xAxis: {
            type: 'category',

            boundaryGap: false,
            axisLabel: {
              left: '40%',
              fontSize: 11.2,
              showMaxLabel: true // 确保显示最后一个标签
            },
            // axisLabel: {
            //   left: '40%',
            //   interval: 0,
            //   rotate: 60
            // }, //文字倾斜解决隔行不显示的问题
            data: []
          },
          yAxis: {
            type: 'value'
          },
          series: []
        };
      });

      chartArr.sort().forEach((year, index) => {
        const currentYearData = sourceMap[year];
        optionArr[index].xAxis.data = [...currentYearData.dateArr];
        currentYearData.dateArr.sort().forEach((date, idx) => {
          if (isOption2) {
            if (idx == 0) {
              optionArr[index].series[0] = {
                name: '',
                type: 'line',
                smooth: true,
                data: []
              };
            }
            const current = sourceMap[year][date] || '';
            if (current) {
              optionArr[index].series[0].data.push(current.soilMoisture);
            } else {
              optionArr[index].series[0].data.push(0);
            }
          } else {
            // 单独小区
            if (this.query.areaCode) {
              if (!optionArr[index].legend.data.includes(this.query.areaCode)) {
                optionArr[index].legend.data.push(this.query.areaCode + '号小区');
              }
              optionArr[index].series[0] = {
                name: '土壤含水量',
                type: 'line',
                smooth: true,
                data: []
              };
              currentYearData.dateArr.forEach((date) => {
                optionArr[index].series[0].data.push(currentYearData[this.query.areaCode][date].soilMoisture);
              });
            } else {
              // 所有数据
              if (idx == 0) {
                this.areaCodeList.forEach((areaCode, _index) => {
                  optionArr[index].legend.data.push(areaCode.label);
                  optionArr[index].series[_index] = {
                    name: areaCode.label,
                    type: 'line',
                    smooth: true,
                    data: []
                  };
                });
              }
              // 遍历小区
              this.areaCodeList.forEach((areaCode, _index) => {
                const current = sourceMap[year][areaCode.areaCode][date] || '';
                if (current) {
                  optionArr[index].series[_index].data.push(current.soilMoisture);
                } else {
                  optionArr[index].series[_index].data.push(0);
                }
              });
            }
          }
        });
      });
      if (!leftChart) {
        leftChart = echarts.init(document.getElementById('leftChart'));
        if (leftChart) {
          window.addEventListener('resize', function () {
            leftChart.resize();
          });
        }
      } else {
        leftChart.clear();
      }
      if (chartArr[1]) {
        if (rightChart) {
          rightChart.clear();
        } else {
          rightChart = echarts.init(document.getElementById('rightChart'));
          if (rightChart) {
            window.addEventListener('resize', function () {
              rightChart.resize();
            });
          }
        }
      } else {
        if (rightChart) {
          rightChart.clear();
        }
      }
      if (leftChart && optionArr[0]) leftChart.setOption(optionArr[0]);
      if (rightChart && optionArr[1]) rightChart.setOption(optionArr[1]);
      this.showCharts = true;
    },
    getchecktype() {
      let that = this;
      sysdictviewlistDictItem({
        dictCode: 'ZD-000004'
      })
        .then((e) => {
          that.checkArr = e.object;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getstationData() {
      let data = {
        currentPage: 1,
        pageSize: 1000
      };
      viewPageStationInfo(data).then((res) => {
        this.stationData = res.object.dataList;
      });
    },
    typeChange() {
      this.query.stcd = '';
    }
  }
};
</script>

<style lang="less" scoped>
.content-common {
  padding-left: 30px;
  padding-right: 30px;
  padding-top: 25px;
}
.search-top {
  margin-bottom: 20px;
  border-bottom: 2px solid #ebebeb;
}

.header-title {
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 24px;
  color: #252b46;
  line-height: 33px;
  text-align: center;
  font-style: normal;
}
.data-preview {
  display: flex;
  justify-content: space-between;
}
.preview-item {
  width: 711px;
  // height: 108px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #252b46;
  line-height: 20px;
  text-align: left;
  font-style: normal;
  padding: 5px 20px 5px 10px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .el-button {
    margin-left: 31px;
    width: 68px;
    height: 30px;
    border-radius: 15px;
    color: #fff;
  }
  span {
    // font-family: Impact;
    font-size: 18px;
    font-weight: bold;
    &.total {
      color: #ff7e42;
      line-height: 20px;
    }
  }
}

.left-dot {
  position: relative;
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background: #252b46;
  margin-right: -1px;
  top: -4px;
}
.left {
  height: 500px;
  display: flex;
  text-align: left;
  width: 49%;
}
.right {
  height: 500px;
  display: flex;
  text-align: right;
  width: 49%;
}
</style>

